import {
  postLoginApi
} from "../../../https/user"

// pages/login/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 顶部标题栏动态设置
    topBarInfo: {
      navBarHeight: app.globalData.navBarHeight,
      menuRight: app.globalData.menuRight,
      menuTop: app.globalData.menuTop,
      menuHeight: app.globalData.menuHeight,
    },
    auth: true,
    email: '',
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  // 登录按钮
  async loginBtn() {
    const {
      email,
      password,
      auth
    } = this.data
    if (!this.isEmail(email)) {
      wx.showToast({
        title: '请输入正确的邮箱',
        icon: 'none'
      })
      return
    }
    if (password.length > 16 || password.length < 8) {
      wx.showToast({
        title: '密码长度为8-16位字符',
        icon: 'none'
      })
      return
    }
    if (!auth) {
      wx.showToast({
        title: '请同意注册隐私协议',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '登录中..',
      mask: true,
    })
    const postRes = await postLoginApi({
      email,
      password
    })
    console.log(postRes)
    if (postRes.code == 200) {
      wx.setStorageSync('token', 'Bearer ' + postRes.data)
      wx.showToast({
        title: '登录成功',
        icon: 'success',
        mask: true
      })
      setTimeout(() => {
        wx.reLaunch({
          url: '../index/index',
        })
      }, 600)
    } else {
      wx.showToast({
        title: postRes.message,
        icon: 'none'
      })
      return
    }
  },
  // input输入框
  changeInput(e) {
    const value = e.detail.value
    const type = e.currentTarget.dataset.type
    this.setData({
      [type]: value
    })
    console.log(this.data)
  },
  // 切换授权
  toggleAuth() {
    this.setData({
      auth: !this.data.auth
    })
  },
  // 邮箱格式验证
  isEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  },
  // 跳转注册
  gotoRegister() {
    wx.navigateTo({
      url: '../register/index',
    })
  },
  // 跳转忘记密码
  gotoReset() {
    wx.navigateTo({
      url: '../reset/index',
    })
  },
  // 返回上一页
  back() {
    wx.navigateBack()
  }

})